#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES uTextureSampler;
uniform sampler2D sMaskTexture;//mask纹理内容数据
varying vec2 vTextureCoord;//相机的纹理坐标，这里已经被transform矩阵处理过了
varying vec2 vMaskTextureCoord;//Mask的纹理坐标
void main()
{
  vec4 vCameraColor = texture2D(uTextureSampler, vTextureCoord);
//  float fGrayColor = (0.3*vCameraColor.r + 0.59*vCameraColor.g + 0.11*vCameraColor.b);
//  gl_FragColor = vec4(fGrayColor, fGrayColor, fGrayColor, 1.0);
  vec4 vMaskColor = texture2D(sMaskTexture, vTextureCoord);

  //模糊化，黑的地方全模糊，白的全不模糊
  //经过测试发现 samplerExternalOES和 sampler2D 不能叠加，
  //非常奇怪,找到原因了，是外面glUniform1i第二个参数设置成相同的了

  //先做一个全模糊==================================================================================
  //给出卷积内核中各个元素对应像素相对于待处理像素的纹理坐标偏移量
  vec2 offset0=vec2(-1.0, -1.0); vec2 offset1=vec2(0.0, -1.0); vec2 offset2=vec2(1.0, -1.0);
  vec2 offset3=vec2(-1.0, 0.0); vec2 offset4=vec2(0.0, 0.0); vec2 offset5=vec2(1.0, 0.0);
  vec2 offset6=vec2(-1.0, 1.0); vec2 offset7=vec2(0.0, 1.0); vec2 offset8=vec2(1.0, 1.0);


  //模糊卷积内核中各个位置的值的权重
  float kernelValue0 = 0.045; float kernelValue1 = 0.056; float kernelValue2 = 0.045;
  float kernelValue3 = 0.056; float kernelValue4 = 0.071; float kernelValue5 =0.056;
  float kernelValue6 = 0.045; float kernelValue7 = 0.056; float kernelValue8 = 0.045;

  float scaleFactor = 1.0/(kernelValue0 +kernelValue1 +kernelValue2 +
                                  kernelValue3 +kernelValue4 +kernelValue5 +
                                  kernelValue6 +kernelValue7 +kernelValue8 );//给出最终求和时的加权因子(为调整亮度)
  vec4 sum;//最终的颜色和
  //获取卷积内核中各个元素对应像素的颜色值
  vec4 cTemp0, cTemp1, cTemp2, cTemp3, cTemp4, cTemp5, cTemp6, cTemp7, cTemp8;
  //这里使用256，居然产生了网格？单目虚化范围扩大的网格？
  float scale = 350.0;
  //这里除以scale的意思实际上是指虚化的范围，如果是400，表示把纹理分成400*400的网格
  //然后在这个网格上，根据上面设定的纹理坐标偏移量进行采图，数值越小，表示跨度越大，虚化力度越大，越容易出现网格
  cTemp0=texture2D(uTextureSampler, vTextureCoord.st + offset0.xy/scale);
  cTemp1=texture2D(uTextureSampler, vTextureCoord.st + offset1.xy/scale);
  cTemp2=texture2D(uTextureSampler, vTextureCoord.st + offset2.xy/scale);
  cTemp3=texture2D(uTextureSampler, vTextureCoord.st + offset3.xy/scale);
  cTemp4=texture2D(uTextureSampler, vTextureCoord.st + offset4.xy/scale);
  cTemp5=texture2D(uTextureSampler, vTextureCoord.st + offset5.xy/scale);
  cTemp6=texture2D(uTextureSampler, vTextureCoord.st + offset6.xy/scale);
  cTemp7=texture2D(uTextureSampler, vTextureCoord.st + offset7.xy/scale);
  cTemp8=texture2D(uTextureSampler, vTextureCoord.st + offset8.xy/scale);
  //颜色求和
  sum =kernelValue0*cTemp0+kernelValue1*cTemp1+kernelValue2*cTemp2+
  kernelValue3*cTemp3+kernelValue4*cTemp4+kernelValue5*cTemp5+
  kernelValue6*cTemp6+kernelValue7*cTemp7+kernelValue8*cTemp8;

  //其他普通卷积
  vec4 blurColor = sum * scaleFactor;//进行亮度加权后将最终颜色传递给渲染管线

  //mix(x,y,a) 返回 x*(1-a)+y*a,所以a代表y的比例
  //mask色值中1表示背景，0表示内容
  gl_FragColor = mix(vCameraColor, blurColor, vMaskColor);
//  gl_FragColor = vMaskColor;
}
